<template>
  <div class="change-password-container">
    <el-card class="password-card">
      <div slot="header" class="card-header">
        <span>修改密码</span>
      </div>
      <el-form ref="passwordForm" :model="passwordForm" :rules="rules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleChangePassword">确认修改</el-button>
          <el-button @click="$router.push('/profile')">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { changePassword } from '@/api/user'

export default {
  name: 'ChangePassword',
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleChangePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          const { confirmPassword, ...passwordData } = this.passwordForm
          changePassword(passwordData)
            .then(() => {
              this.$message.success('密码修改成功，请重新登录')
              this.$store.dispatch('user/logout').then(() => {
                this.$router.push('/login')
              })
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.change-password-container {
  padding: 20px;

  .password-card {
    max-width: 600px;
    margin: 0 auto;

    .card-header {
      font-size: 18px;
      font-weight: bold;
    }

    .el-button {
      margin-right: 20px;
    }
  }
}
</style> 